# encoding=utf-8

# 这里编写所有关于后台的运行脚本
import os

import invoke
import sys
from seg_system import ApplicationConfig

on_win = sys.platform.startswith("win")


def print_banner(msg):
    invoke.run('echo “==================================================”')
    invoke.run('echo "= {}"'.format(msg))
    invoke.run('echo “==================================================”')


@invoke.task()
def start_service(c):
    print_banner('service now starting!!!')
    invoke.run('nohup python app2.py > nohup.out')  # 修增远程重启后, 退出导致文件写入失败的问题


@invoke.task()
def start_frpc(c):
    print_banner('start frpc !!!!')
    invoke.run('nohup {} -c {} & >> {}'.format(
        os.path.join(ApplicationConfig.SystemConfig.FRP_PATH, ApplicationConfig.SystemConfig.FRP_EXEC),
        os.path.join(ApplicationConfig.SystemConfig.FRP_PATH, ApplicationConfig.SystemConfig.FRP_CONFIG),
        os.path.join(ApplicationConfig.SystemConfig.FRP_PATH, ApplicationConfig.SystemConfig.FRP_LOG)
    ))


@invoke.task()
def stop_service(c):
    res = invoke.run('lsof -i:{}'.format(ApplicationConfig.SystemConfig.SERVER_PORT))
    res_list = res.stdout.split()
    python_list = []
    for index in range(len(res_list)):
        if 'python' in res_list[index]:
            t = (res_list[index], res_list[index + 1])
            if t not in python_list:
                python_list.append(t)

    print_banner('list below will be stop by forced')
    print_banner(str(python_list))
    for each_python in python_list:
        invoke.run('kill -9 {}'.format(each_python[1]))


# if __name__ == '__main__':
#     stop_service()
